package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        Date date = new Date();
        member.setRegTime(date);
        String password = member.getPassword();
        if(password != null){
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        member.setRegTime(date);
        memberDao.add(member);
    }

    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for(String month: months){
            String date = month + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page=memberDao.findPage(queryPageBean.getQueryString());

        List<Member> memberList = page.getResult();
        for (Member member : memberList) {
            member.setAge(getAge(member.getBirthday()));
            String healthManagerName=memberDao.findHealthManagerById(member.getHealthManagerId());
            member.setHealthManagerName(healthManagerName);
        }
        return new PageResult(page.getTotal(), memberList);

    }

    @Override
    public void delete(Integer id) throws Exception{
        Integer count = memberDao.findSetMealIdsByMemberId(id);
        if (count > 0) {
            throw new RuntimeException("当前项被"+count+"个套餐引用,不能删除");
        }
        memberDao.deleteById(id);
    }

    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override
    public List<Member> findAll() {
        return memberDao.findAll();
    }

    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> getMemberReport(Integer[] memberIds) {
        List<Map<String,Object>>result=new ArrayList<>();

        List<Member>members=memberDao.findMemberById(memberIds);
        for (Member member : members) {
            Integer id=member.getId();
            if (id == null){
                break;
            }
            String memberName=member.getName();
            String memberSex=member.getSex();
            String memberPhoneNumber=member.getPhoneNumber();
            List<String> list=new ArrayList<>();
            list=memberDao.findByDeptById(member.getId());
            String setmealName=null;
            if (member.getOrder()!=null){
                Setmeal setmeal=member.getOrder().getSetmeal();
                if (setmeal!=null){
                    setmealName =setmeal.getName();
                }
            }

            List<String>groupNames=new ArrayList<>();
            List<String>itemNames=new ArrayList<>();

            /*System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"+members);*/

            List<CheckGroup> checkGroups=null;
            if (member.getOrder()!=null){
                Setmeal setmeal=member.getOrder().getSetmeal();
                if (setmeal!=null){
                    checkGroups=setmeal.getCheckGroups();
                }
            }
            if (checkGroups!=null) {
                for (CheckGroup checkGroup : checkGroups) {
                    String groupName = checkGroup.getName();
                    groupNames.add(groupName);

                    List<CheckItem> checkItems = checkGroup.getCheckItems();
                    for (CheckItem checkItem : checkItems) {
                        String itemName = checkItem.getName();
                        itemNames.add(itemName);
                    }
                }
            }
            Map<String,Object> map=new HashMap<>();
            map.put("memberName",memberName);
            map.put("memberSex",memberSex=="1"?"男":memberSex=="2"?"女":"未知");
            map.put("memberPhoneNumber",memberPhoneNumber);
            map.put("address",list);
            map.put("setmealName",setmealName);
            map.put("groupNames",groupNames);
            map.put("itemName",itemNames);
            result.add(map);

        }
        System.out.println(result);
        return result;
    }

    @Override
    public List<Map> getManagers() {
       return memberDao.getManagers();
    }

    public int getAge(Date birthDay) throws Exception {
        if(birthDay==null){
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;//计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            }else{
                age--;//当前月份在生日之前，年龄减一

            } } return age; }
    //根据手机号和用户输入的两个日期进行查询
    public List<DateSetmeal> findByDate(Map map, String telephone) {
        // 将手机号再放进map集合,再传给dao
        map.put("telephone",telephone);
        return memberDao.findByDate(map);
    }
    //查询会员预约所有信息，包括预约方式，预约地址等等
    @Override
    public List<DateSetmeal> findByOid(String telephone, Integer oid) {
        Map<String,Object> map=new HashMap<>();
        map.put("telephone",telephone);
        map.put("oid",oid);
        return memberDao.findByOid(map);
    }

    @Override
    public List<Map<String, Object>> findMemberAge() {
        return memberDao.findAgeByBirthday();
    }

    @Override
    public List<Map<String, Object>> findAgeByBirthday() {
        return memberDao.findAgeByBirthday();
    }


}
